import 'dart:convert';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:maihealth/class/login/page/loginPage.dart';
import 'package:maihealth/class/login/provide/loginProvide.dart';
import 'package:maihealth/utils/router.dart';
import 'package:maihealth/utils/toast.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:async';

/*
 * 封装 restful 请求
 * 
 * GET、POST、DELETE、PATCH
 * 主要作用为统一处理相关事务：
 *  - 统一处理请求前缀；
 *  - 统一打印请求信息；
 *  - 统一打印响应信息；
 *  - 统一打印报错信息；
 */
class HttpUtils{
  /// global dio object
  static Dio dio;

  /// default options
  static const String API_PREFIX = 'http://dev.haomaijk.com';
  static const int CONNECT_TIMEOUT = 10000;//连接时间
  static const int RECEIVE_TIMEOUT = 3000;//接收时间

  /// http request methods
  static const String GET = 'get';
  static const String POST = 'post';
  static const String PUT = 'put';
  static const String PATCH = 'patch';
  static const String DELETE = 'delete';
  static String COOKIEPATH;
  /// request method
  static Future<Map> post (String path, {Map params}) async {
    params = params ?? {};

    String url =  API_PREFIX + path;//请求全路径
    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：${url}');
    print('请求参数：${params}');

    Dio dio = createInstance();
    var result;
    try {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
      Options options = new Options(
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
        method: POST
      );
      dio.interceptors.add(CookieManager(PersistCookieJar(dir:COOKIEPATH)));
      Response response = await dio.request(url, data: params, options: options);
      result = response.data;
      String  str= json.encode(result);
      print('请求结果:${str}');
      if (result['status']=='200') {
         return result;
      }else if (result['status']=='401') {
          showToast(result['msg']);
          Router.changeRootPage(null,loginPage());
          loginProvide().exitLogin();
          throw('重新登录');
      }else{
          throw(result['msg']);
      }
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
      throw('网络中断~~');
    } 
  }

static  getCookiePath()async{
    getApplicationDocumentsDirectory().then((appDocDir){
          print('cookiePath===${appDocDir.path}');
          COOKIEPATH = appDocDir.path;
   });
}
/// request method
  static Future<Map> get (String path, {Map params}) async {
    params = params ?? {};
    String url =  API_PREFIX + path;//请求全路径
    /// restful 请求处理   
    /// /gysw/search/hist/:user_id        user_id=27
    /// 最终生成 url 为     /gysw/search/hist/27
    params.forEach((key, value) {
      if (path.indexOf(key) != -1) {
        path = path.replaceAll(':$key', value.toString());
      }
    });
    /// 打印请求相关信息：请求地址、请求方式、请求参数
    print('请求地址：${url}');
    print('请求参数：${params}');

    Dio dio = createInstance();
    var result;
    try {
      /// 全局属性：请求前缀、连接超时时间、响应超时时间
    Options options = new Options(
        connectTimeout: CONNECT_TIMEOUT,
        receiveTimeout: RECEIVE_TIMEOUT,
        method: GET
      );
      dio.interceptors.add(CookieManager(PersistCookieJar(dir:COOKIEPATH)));
      Response response = await dio.request(url, data: params, options: options);
      result = response.data;
      String  str= json.encode(result);
      print('请求结果:${str}');
     if (result['status']=='200') {
         return result;
      }else if (result['status']=='401') {
          showToast(result['msg']);
          Router.changeRootPage(null,loginPage());
          loginProvide().exitLogin();
          throw('重新登录');
      }else{
          throw(result['msg']);
      }
    } on DioError catch (e) {
      /// 打印请求失败相关信息
      print('请求出错：' + e.toString());
      throw('网络中断~~');
    }
  }

/// 创建 dio 实例对象
static Dio createInstance (){
  if (dio == null) {
      dio = new Dio();
  }
    return dio;
}
// // 读取 json 数据
// static readJSON(String path) async {
//     try {
//         final file = await localFile(path);
//         String str = await file.readAsString();
//         print('strJson=====${str}'); 
//     }
//     catch (err) {
//         print(err);
//     }
// }

// static localFile(path) async {
//     return new File(path+'/ie0_ps1/dev.haomaijk.com');
// }
  /// 清空 dio 对象
  static clear () {
    dio = null;
  }

}